package com.dullong.firedocmanager.util;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

public class OptionUtil {

	public static String getOption(String key) {
		Connection conn = ConnectionUtil.getConnection();
		QueryRunner runner = new QueryRunner();
		try {
			Object[] obj = runner.query(conn,
					"select option_value from `option` where option_name=?",
					new ArrayHandler(), key);
			if (obj != null)
				return (String) obj[0];
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return null;
	}

	public static List<Map<String, Object>> getAll() {
		Connection conn = ConnectionUtil.getConnection();
		QueryRunner runner = new QueryRunner();
		try {
			return runner.query(conn, "select * from `option`",
					new MapListHandler());

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}
		return null;

	}

	public static void saveOrUpdateOption(String key, String value) {
		Connection conn = ConnectionUtil.getConnection();
		QueryRunner runner = new QueryRunner();
		try {
			runner.update(conn, "replace into `option` values(?,?)", key, value);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(conn);
		}
	}

	public static void main(String[] s) {
		// saveOrUpdateOption("idx_path", "D:/idx_path");
		// System.out.println(getOption("idx_path"));
		List<Map<String, Object>> all = getAll();
		for (Map<String, Object> x : all) {
			System.out.println(x.get("option_name"));
			System.out.println(x.get("option_value"));
			System.out.println("----------------------");

		}
		System.out.println(all);
	}
}
